package edu.cibertec.action;

import java.io.Reader;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

import edu.cibertec.actionform.LoginForm;
import edu.cibertec.bean.UsuarioTO;

import edu.cibertec.action.Blowfish;;

public class LoginAction extends Action {
    
    public ActionForward execute ( ActionMapping mapping,
                                   ActionForm form,
                                   HttpServletRequest request,
                                   HttpServletResponse response)
                                   throws Exception {
    	
    	LoginForm loginForm = (LoginForm)form;
    	String login = loginForm.getLogin();
    	
    	//probando encriptacion
    	String password =loginForm.getPassword();
    	System.out.println(password);
    	password = loginForm.getPassword();//Blowfish.encriptar(password,"AH1N1").toString(); //loginForm.getPassword();
    	
    	loginForm.setPassword(password);
    	
    	//verificando que es diferente de null
    	if ( password != null ) {
    		//System.out.println(password);
    	}
    	else{
    		//System.out.println("nada");
    	}
    	
    	//String pswDesencriptar = Blowfish.desEncriptar(password,"AH1N1"); 
    	//Blowfish.encriptar(frmInscripcion.getPassword(),"AH1N1"); 
    	
     	SqlMapClient sqlMap;

		try {
			String resource = "SqlMapConfigApplication.xml";
			Reader reader = Resources.getResourceAsReader(resource);
			sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(
				"Error cargando configuracion en RegistroAction Cause: "+ e);
		}
		
		
		UsuarioTO usuario = (UsuarioTO)sqlMap.queryForObject("autenticaUsuario", loginForm);
    	
    	if ( usuario != null ) {
    		usuario.setListaOperaciones( (ArrayList)sqlMap.queryForList("getPerfilUsuario",login));
    		HttpSession session = request.getSession();
    		session.setAttribute("usuario", usuario );
    		return mapping.findForward("success");
    	} else {
    		System.out.println("usuario.getApellido_usu() SI es null");
    		System.out.println(password);
    		ActionMessages errors = new ActionMessages();
    		errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("login.msg.invalidLogin"));
    		saveErrors(request, errors );
    		return( mapping.findForward("failure"));
    	}
    	
    }
}
